package com.version1_1.service.implement;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.util.property.Properties;
import com.version1_1.dao.UserDao;
import com.version1_1.service.RongCloudService;
import com.version1_1.service.UserService;

import com.alibaba.fastjson.JSON;
import com.version1_3.service.CoinService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    /*创建log4j对象*/
    private static final Logger LOGGER = Logger.getLogger(UserServiceImpl.class);

    @Autowired
    private UserDao userDao;

    @Autowired
    private RongCloudService rongCloudService;

    @Autowired
    private CoinService coinService;


    /**
     * @param telnumber
     * @param mail
     * @param password
     * @return
     * @name: userRegister
     * @description: 用户注册
     */
    @Override
    public String userRegister(String telnumber, String mail, String password) {

        // 无有效参数
        if ("".equals(telnumber) && "".equals(mail)) {
            LOGGER.error("用户注册,错误代码: 0，无手机号，无邮箱号...");
            return "{\"isCorrect\":false,\"type\":0,\"userId\":-1}";
        }
        // 参数错误
        if (!"".equals(telnumber)) {
            // 手机号已存在
            if (userDao.checkUserExist("", telnumber)) {
                LOGGER.error("用户注册,错误代码: 4,手机号已存在...");
                return "{\"isCorrect\":false,\"type\":4,\"userId\":-1}";
            }
            // 手机号不是11位
            if (telnumber.length() != 11) {
                LOGGER.error("用户注册,错误代码: 2,手机号不是11位...");
                return "{\"isCorrect\":false,\"type\":2,\"userId\":-1}";
            }
        }
        if (!"".equals(mail)) {
            // 邮箱已存在
            if (userDao.checkUserExist(mail, "")) {
                LOGGER.error("用户注册,错误代码: 4,邮箱已存在...");
                return "{\"isCorrect\":false,\"type\":4,\"userId\":-1}";
            }
            // 邮箱格式错误
            Pattern pattern = Pattern
                    .compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
            Matcher matcher = pattern.matcher(mail);
            if (!matcher.matches()) {
                LOGGER.error("用户注册,错误代码: 1,邮箱格式错误...");
                return "{\"isCorrect\":false,\"type\":1,\"userId\":-1}";
            }
        }

        int userId = userDao.userRegister(telnumber, mail, password);
        boolean isCorrect = true;
        // 注册失败
        if (userId == 0) {
            LOGGER.error("用户注册,错误代码: 3,注册失败...");
            return "{\"isCorrect\":false,\"type\":3,\"userId\":-1}";
        }

        userDao.updateUserInviteCode(userId);

        return "{\"isCorrect\":" + isCorrect + ",\"userId\":" + userId + "}";
    }

    /**
     * @param userId
     * @param mail
     * @param telnumber
     * @param password
     * @return
     * @name: userLogin
     * @description: 用户登陆
     */
    @Override
    public String userLogin(int userId, String mail, String telnumber,
                            String password, String baiduId) {

        // 监测是否存在用户，不存在返回错误ID:0
        if (userId < 0 && !userDao.checkUserExist(mail, telnumber)) {
            LOGGER.info("用户登陆,用户不存在或者userID<0...");
            return "{\"userId\":-1,\"errorType\":0}";
        }

        Map<String, Object> userInfoMap = userDao.userLogin(userId, mail,
                telnumber, password);

        // 获取用户token

        String userToken = "";
        /*try {
            userToken = rongCloudService.getToken(Properties.RongCloud_appKey, Properties.RongCloud_appSecret, (int) userInfoMap.get("userId"));
            userToken = JSON.parseObject(userToken).getString("token");
        } catch (Exception exception) {
            LOGGER.error("融云服务器获取userToken出错");
        }*/

        String photoString = "";

        // 登陆失败，返回错误ID:1
        if (userInfoMap == null || userInfoMap.isEmpty()) {
            return "{\"userId\":-1,\"errorType\":1}";
        }

        // 登陆刷新baiduId
        userDao.updateUserBaiduId(baiduId, (int) userInfoMap.get("userId"));

        // 排除用户名为"null"的情况
        if (userInfoMap.get("userName") == null) {
            userInfoMap.put("userName", "");
        }
        // 排除用户头像为"null"的情况
        if (userInfoMap.get("userPhoto") == null) {
            userInfoMap.put("userPhoto", "");
        } else {
            photoString = userInfoMap.get("userPhoto") + Properties.ImageLowQuality;
        }
        // 排除用户收藏为"null"的情况
        if (userInfoMap.get("userCollect") == null) {
            userInfoMap.put("userCollect", "");
        }

        String userInfoString = "{" + "\"userId\":"
                + (int) userInfoMap.get("userId")
                + ","
                + "\"userName\":\""
                + (String) userInfoMap.get("userName")
                + "\","
                + "\"userCoin\":"
                + (int) userInfoMap.get("userCoin")
                + ","
                + "\"height\":"
                + ((BigDecimal) userInfoMap.get("height")).doubleValue()
                + ","
                + "\"weight\":"
                + ((BigDecimal) userInfoMap.get("weight")).doubleValue() + ","
                + "\"userPhoto\":\"" + photoString + "\","
                + "\"userSex\":\"" + (String) userInfoMap.get("userSex") + "\","
                /*这里的userReadedNum值含义为用户收藏文章数，这里设置JSON key为"userCollectedNum"*/
                + "\"userCollectedNum\":"
                + (int) userInfoMap.get("userCollectNumber")
                + ","
                + "\"userCollect\":\"" + (String) userInfoMap.get("userCollect") + "\","
                + "\"token\":\"" + userToken + "\","
                + "\"school\":\"" + (String) userInfoMap.get("school") + "\","
                + "\"schoolYear\":" + (int) userInfoMap.get("schoolYear") + ","
                + "\"registerDate\":\"" + userInfoMap.get("registerDate") + "\"," // 新添字段 registerDate: 用户注册时间
                + "\"userFocusId\":"
                /*
                 * 数据库中存储的用户关注字符串格式为：{"focusList":[...]}
				 */
                + ((String) userInfoMap.get("userFocusId")).substring(13,
                ((String) userInfoMap.get("userFocusId")).length() - 1)
                + "}";

        coinService.recordUserLogin((int) userInfoMap.get("userId")); // 登陆加积分 03.06

        return userInfoString;
    }

    /**
     * @param updateInfoString
     * @return
     * @name: updateUserInfo
     * @description: 更新用户个人信息
     */
    @Override
    public String updateUserInfo(String updateInfoString) {

        try {
            // 从JSON字符串中读取userId,userName,userPhoto,userSex
            JSONObject jsonObject = JSON.parseObject(updateInfoString);
            int userId = jsonObject.getIntValue("userId");
            String userName = jsonObject.getString("userName");
            String userPhoto = jsonObject.getString("userPhoto");
            String userSex = jsonObject.getString("userSex");

            String school = "";
            int schoolYear = -1;
            try {
                school = jsonObject.getString("school");
                schoolYear = jsonObject.getIntValue("schoolYear");
            } catch (JSONException jsonException) {
                LOGGER.error("更新用户个人信息，JSON参数没有school和schoolYear字段");
            }

            return "{\"updateResult\":" + userDao.updateUserInfo(userId, userName, userPhoto, userSex, school, schoolYear) + "," + userDao.getUserInfo(userId).toString() + "}";

        } catch (Exception exception) {
            // JSON字符串中缺少key
            LOGGER.error("更新用户个人信息,JSON字符串缺少Key...", exception);
            return "{\"updateResult\":false}";
        }
    }

    /**
     * @param updateListString
     * @return
     * @name: updateFocusList
     * @description: 更新用户关注列表
     */
    @Override
    public String updateFocusList(String updateListString) {
        boolean result = userDao.updateFocusList(updateListString);
        return "{\"focusUpdateResult\":" + result + "}";
    }

    /**
     * @param updateListString
     * @return
     * @Description: TODO(更新关注列表，新接口)
     */
    @Override
    public String updateFocusListNew(String updateListString) {
        JSONObject updateFocusJson = JSON.parseObject(updateListString);

        int userId = updateFocusJson.getIntValue("userId");
        JSONArray updateFocusJsonArray = updateFocusJson.getJSONArray("updateFocusList");


        return null;
    }

    /**
     * @param userId
     * @param pageNumber
     * @param pageSize
     * @return
     * @name: getReplyString
     * @description: 获取用户回复消息列表
     */
    @Override
    public String getReplyString(int userId, int pageNumber, int pageSize) {
        List replyList = userDao.getReplyList(userId, pageNumber, pageSize);
        String userPhotoStr = "";

        // 回复列表为空或者获取回复列表错误
        if (replyList == null || replyList.isEmpty()) {
            return "{\"isLast\":true,\"replyList\":[]}";
        }

        // 组合JSON字符串
        String replyListString = "{\"isLast\":false,\"replyList\":[";
        for (int i = 0; i < replyList.size(); i++) {
            Map replyMap = (Map) replyList.get(i);
            int commentId = (int) replyMap.get("commentId");
            String replyerName = (String) replyMap.get("userName");
            String replyerPhoto = (String) replyMap.get("userPhoto");
            String replyContent = (String) replyMap.get("replyContent");
            String comment = (String) replyMap.get("comment");
            String date = (String) replyMap.get("date");
            int pageId = (int) replyMap.get("pageId");

            // 排除用户名为"null"的情况
            if (replyerName == null) {
                replyerName = "";
            }
            // 排除用户头像为"null"的情况
            if (replyerPhoto == null) {
                userPhotoStr = "";
            } else {
                userPhotoStr = replyerPhoto + Properties.ImageLowQuality;
            }

            String tempString = "{" + "\"commentId\":" + commentId + ","
                    + "\"replyerName\":\"" + replyerName + "\","
                    + "\"replyerPhoto\":\"" + userPhotoStr + "\","
                    + "\"replyContent\":\"" + replyContent + "\","
                    + "\"comment\":\"" + comment + "\"," + "\"date\":\"" + date
                    + "\"," + "\"pageId\":" + pageId + "},";
            replyListString = replyListString.concat(tempString);
        }

        replyListString = replyListString.substring(0,
                replyListString.length() - 1);
        return replyListString.concat("]}");
    }

    /**
     * @param updatePasswdString
     * @return
     * @name: updatePasswd
     * @description: 更改密码
     */
    @Override
    public String updatePasswd(String updatePasswdString) {
        JSONObject jsonObject = JSON.parseObject(updatePasswdString);
        boolean updatePasswdResult = userDao.updatePasswd(
                jsonObject.getIntValue("userId"),
                jsonObject.getString("newPasswd"));

        if (updatePasswdResult) {
            return "{\"updatePasswdResult\":true}";
        } else {
            return "{\"updatePasswdResult\":false}";
        }
    }

    /**
     * @param userId
     * @param pageNumber
     * @param pageSize
     * @return
     * @name: getPraiseString
     * @description: 获取点赞列表信息数据
     */
    @Override
    public String getPraiseString(int userId, int pageNumber, int pageSize) {
        List praiseList = userDao.getPraiseList(userId, pageNumber, pageSize);

        /*获取点赞列表错误或者点赞列表为空*/
        if (praiseList == null || praiseList.isEmpty()) {
            return "{\"isLast\":true,\"praiseList\":[]}";
        }

        String praiseListString = "{\"isLast\":false,\"praiseList\":[";
        for (int i = 0; i < praiseList.size(); i++) {
            Map replyMap = (Map) praiseList.get(i);
            String praiserName = (String) replyMap.get("userName");
            String praiserPhoto = (String) replyMap.get("userPhoto");
            String comment = (String) replyMap.get("comContent");
            String date = (String) replyMap.get("date");

            // 排除用户名为"null"的情况
            if (praiserName == null) {
                praiserName = "";
            }
            // 排除用户头像为"null"的情况
            if (praiserPhoto == null) {
                praiserPhoto = "";
            }

            String tempString = "{" + "\"praiserName\":\"" + praiserName
                    + "\"," + "\"praiserPhoto\":\"" + praiserPhoto + Properties.ImageLowQuality + "\","
                    + "\"comment\":\"" + comment + "\"," + "\"date\":\"" + date
                    + "\"},";
            praiseListString = praiseListString.concat(tempString);
        }

        praiseListString = praiseListString.substring(0,
                praiseListString.length() - 1);
        return praiseListString.concat("]}");
    }

    /**
     * @param feedbackString
     * @return
     * @name: feedback
     * @description: 用户反馈
     */
    @Override
    public String feedback(String feedbackString) {
        JSONObject feedbackJson = JSON.parseObject(feedbackString);
        int userId = feedbackJson.getIntValue("userId");
        String feedbackType = feedbackJson.getString("feedbackType");
        String feedbackDate = feedbackJson.getString("feedbackDate");
        String feedbackContent = feedbackJson.getString("feedbackContent");

        /*截图最多4张，image采用String字符串数据格式*/
        String screenShot1 = (feedbackJson.getString("screenShot1") == null) ? null : feedbackJson.getString("screenShot1");
        String screenShot2 = (feedbackJson.getString("screenShot2") == null) ? null : feedbackJson.getString("screenShot2");
        String screenShot3 = (feedbackJson.getString("screenShot3") == null) ? null : feedbackJson.getString("screenShot3");
        String screenShot4 = (feedbackJson.getString("screenShot4") == null) ? null : feedbackJson.getString("screenShot4");


        /*boolean feedbackResult = userDao.feedback(userId, feedbackType,
                feedbackDate, feedbackContent, screenShot1, screenShot2, screenShot3, screenShot4);*/

        return "{\"feedbackResult\":" + userDao.feedback(userId, feedbackType,
                feedbackDate, feedbackContent, screenShot1, screenShot2, screenShot3, screenShot4) + "}";

    }

    /**
     * @param collectString
     * @return
     * @name: doCollect
     * @description: 记录用户收藏
     */
    @Override
    public String doCollect(String collectString) {
        JSONObject jsonObject = JSON.parseObject(collectString);
        boolean doCollectResult = false;
        try {
            int userId = jsonObject.getIntValue("userId");
            int pageId = jsonObject.getIntValue("pageId");
            int actionType = jsonObject.getIntValue("actionType");

            doCollectResult = userDao.doCollect(userId, pageId, actionType);
        } catch (EmptyResultDataAccessException exception) {
            LOGGER.error("记录用户收藏,解析collectString错误...", exception);
        }

        return "{\"collectResult\":" + doCollectResult + "}";
    }


    /**
     * @param userId
     * @return
     * @name: getCollectList
     * @description: 登录用户得到收藏列表
     */
    @Override
    public String getCollectList(int userId, int pageNumber) {
        List<Map<String, Object>> collectList = userDao.getCollectList(userId, pageNumber);
        Map<String, Object> collectMap = new HashMap<>(); // 数据Map

        // 如果收藏列表为空或者获取错误
        if (collectList == null || collectList.isEmpty()) {
            LOGGER.info("用户收藏列表为空或为null...");
            return "{\"collectList\":[]}";
        }

        String secondTypeID = ""; //二级分类名称
        Map<String, Object> secondNameMap = new HashMap<>(); //二级分类名称和数量Map

        /**
         * 对图片URL进行处理
         */
        for (Map<String, Object> tempMap : collectList) {
            tempMap.replace("imageSrc", tempMap.get("imageSrc") + Properties.ImageLowQuality);
        }

        /**
         * 如果是第一页
         */
        if (pageNumber == 1) {

            /*获取总的收藏数据*/
            List collectListAll = userDao.getCollectList(userId);

            // 如果收藏列表为空或者获取错误
            if (collectListAll == null || collectListAll.isEmpty())
                return "{\"collectList\":[]}";

            for (int i = 0; i < collectListAll.size(); i++) {
                Map replyMap = (Map) collectListAll.get(i);
                String thirdTypeName = (String) replyMap.get("thirdTypeName");

            /*----------------分析二级分类名称和数量----------------*/
                secondTypeID = userDao.getSecondIdByThirdName(thirdTypeName);

                if (secondTypeID != null) {
                    if (!secondNameMap.containsKey(secondTypeID)) {
                        LOGGER.info("secondType: " + secondTypeID + "MapSize: " + secondNameMap.size());
                        secondNameMap.put(secondTypeID, 1);
                    } else {
                        LOGGER.info("secondTypeID: " + secondTypeID + "MapSize: " + secondNameMap.size());
                        secondNameMap.put(secondTypeID, (int) secondNameMap.get(secondTypeID) + 1);
                    }
                }
            }

            net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(secondNameMap);
            collectMap.put("count", collectListAll.size());
            collectMap.put("secondTypeList", jsonArray);
        }

        collectMap.put("collectList", collectList);

        return net.sf.json.JSONObject.fromObject(collectMap).toString();
    }

    /**
     * @param userId
     * @param secondType
     * @param pageNumber
     * @return
     * @Description: (根据二级分类ID获取用户收藏中特定的二级分类的文章)
     */
    @Override
    public String getSecondTypeCollectList(int userId, int secondType, int pageNumber) {
        List secondCollectList = userDao.getSecondCollectList(userId, secondType, pageNumber);

        // 如果二级分类收藏列表为空或者获取错误
        if (secondCollectList == null || secondCollectList.isEmpty()) {
            return "{\"secondCollectList\":[]}";
        }

        // 组装收藏列表JSON字符串
        String secondCollectListString = "{\"secondCollectList\":[";

        for (int i = 0; i < secondCollectList.size(); i++) {
            Map replyMap = (Map) secondCollectList.get(i);
            long collectId = (long) replyMap.get("collectId");
            int pageId = (int) replyMap.get("pageId");
            String firstTitle = (String) replyMap.get("firstTitle");
            int secondTypeID = (int) replyMap.get("secondType"); //新添secondType 方便客户端显示
            String thirdTypeName = (String) replyMap.get("thirdTypeName");
            String date = (String) replyMap.get("date");
            String imageSrc = (String) replyMap.get("imageSrc");
            int collectNumber = (int) replyMap.get("collectNumber");

            String tempString = "{"
                    + "\"collectId\":" + collectId + ","
                    + "\"pageId\":" + pageId + ","
                    + "\"firstTitle\":\"" + firstTitle + "\","
                    + "\"secondType\":" + secondTypeID + ","
                    + "\"thirdTypeName\":\"" + thirdTypeName + "\","
                    + "\"date\":\"" + date + "\","
                    + "\"collectNumber\":" + collectNumber + ","
                    /*收藏列表发图片url*/
                    + "\"imageSrc\":\"" + imageSrc + Properties.ImageLowQuality
                    + "\"},";
            secondCollectListString = secondCollectListString.concat(tempString);
        }

        secondCollectListString = secondCollectListString.substring(0, secondCollectListString.length() - 1);
        return secondCollectListString.concat("]}");
    }

    /**
     * @param userId
     * @param deleteList
     * @return {"delResult":true/false}
     * @name: delCollect
     * @description: 登陆用户删除收藏
     */
    @Override
    public String delCollect(int userId, String deleteList) {
        boolean delCollectResult = userDao.delCollect(userId, deleteList);
        return "{\"delResult\":" + delCollectResult + "}";
    }

    /**
     * @param userId
     * @return true,"hasPraise":true/false,"hasReply":true/false,"hasSysMessage":true/false
     * @name: getMessage
     * @description: 得到用户消息状态
     */
    @Override
    public String getMessage(int userId) {
        return userDao.checkMessage(userId);
    }

    /**
     * 检测用户输入的手机号或者邮箱号是否已经被注册
     *
     * @param registerInfo
     * @return
     */
    @Override
    public boolean checkRegister(String registerInfo) {
        int flag = 0; // 标识传入的是邮箱还是手机号 0表示是手机号,1表示是邮箱号
        if (registerInfo.contains("@")) {
            flag = 1;
        }
        return userDao.checkRegister(registerInfo, flag);
    }

    /**
     * 忘记密码
     *
     * @param telnumber
     * @param newPassword
     * @return
     */
    @Override
    public boolean forgetPass(String telnumber, String newPassword) {
        return userDao.forgetPass(telnumber, newPassword);
    }


    /**
     * @param userId
     * @return 1. 如果没有系统消息或者获取消息错误: {"sysMessageList":[]}
     * 2. 如果有系统消息: {"sysMessageList":[{"message":"","date":""}...]}
     * @name: getSystemMessage
     * @description: 获取系统消息
     */
    @Override
    public String getSystemMessage(int userId) {
        List sysMessageList = userDao.getSystemMessageList(userId);

        /*如果没有系统消息或者获取消息错误*/
        if (sysMessageList == null || sysMessageList.isEmpty())
            return "{\"sysMessageList\":[]}";

        String sysMessListString = "{\"sysMessageList\":[";
        for (int i = 0; i < sysMessageList.size(); i++) {
            Map replyMap = (Map) sysMessageList.get(i);
            String message = (String) replyMap.get("message");
            String date = (String) replyMap.get("date");

            String tempString = "{" + "\"message\":\"" + message + "\","
                    + "\"date\":\"" + date + "\"},";
            sysMessListString = sysMessListString.concat(tempString);
        }

        sysMessListString = sysMessListString.substring(0,
                sysMessListString.length() - 1);
        return sysMessListString.concat("]}");
    }

}
